function shipWithinDays(weights: number[], days: number): number {
  let l = Math.max(...weights);
  let r = weights.reduce((a, b) => a + b);
  while (l <= r) {
    const mid = Math.floor((l + r) / 2);
    let sum = 0;
    let d = 1;

    for (const weight of weights) {
      if (sum + weight <= mid) {
        sum += weight;
      } else {
        sum = weight;
        d++;
      }
    }

    if (d > days) {
      l = mid + 1;
    } else {
      r = mid - 1;
    }
  }

  return l;
}
